/*
 * @lc app=leetcode.cn id=671 lang=typescript
 *
 * [671] 二叉树中第二小的节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findSecondMinimumValue(root: TreeNode | null): number {
    if (!root) return -1;
    let min = Infinity;
    const tra = (root: TreeNode) => {
        if (root.left) {
            const bigger = Math.max(root.left.val, root.right!.val);
            if (bigger !== root.val) {
                min = Math.min(bigger, min);
            }
            if (root.left.val === root.val) {
                tra(root.left!);
            }
            if (root.right!.val === root.val) {
                tra(root.right!);
            }
        }
    };
    tra(root);
    if (min === Infinity) return -1;
    if (min === root.val) return -1;
    return min;
}
// @lc code=end
